package com.auicyh.tylb.comm;


import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;

/**
 * 作者：  Ocean 2017/11/3 14:44
 * 功能：  串口检索工类,获取所有串口驱动地址
 * Q Q：   1126067113
 * 修改：
 * @author Ocean
 */

public class SerialPortFinder {
    /** 驱动列表 */
    private Vector<SerialDriver> mDrivers;

    /**
     * 获取驱动列表
     * @return 驱动列表集合
     * @throws IOException IO异常
     */
    public Vector<SerialDriver> getDrivers() throws IOException {
        if (mDrivers == null) {
            mDrivers = new Vector<>();
            // 行号读取者 proc Linux 虚拟文件目录
            LineNumberReader reader = new LineNumberReader(new FileReader("/proc/tty/drivers"));
            String line;
            while ((line = reader.readLine()) != null) {
                // Issue 3: Since driver name may contain spaces, we do not extract driver name with split()
                String driverName = line.substring(0, 0x15).trim();
                String[] dev = line.split(" +");
                if ((dev.length >= 5) && ("serial".equals(dev[dev.length - 1]))) {
                    mDrivers.add(new SerialDriver(driverName, dev[dev.length - 4]));
                }
            }
            reader.close();
        }
        return mDrivers;
    }

    /**
     * 获取所有设备
     * @return 设备列表
     */
    public String[] getAllDevices() {
        Vector<String> devices = new Vector<String>();
        // Parse each driver
        Iterator<SerialDriver> itdriv;
        try {
            itdriv = getDrivers().iterator();
            while (itdriv.hasNext()) {
                SerialDriver driver = itdriv.next();
                for (File file : driver.getDrivers()) {
                    String device = file.getName();
                    String value = String.format("%s (%s)", device,
                            driver.getDriverName());
                    devices.add(value);
                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return devices.toArray(new String[0]);
    }

    /**
     * 获取所有设备路径
     * @return 串口设备路径
     */
    public String[] getAllDevicesPath() {
        Vector<String> devices = new Vector<>();
        // Parse each driver
        Iterator<SerialDriver> itdriv;
        try {
            itdriv = getDrivers().iterator();
            while (itdriv.hasNext()) {
                SerialDriver driver = itdriv.next();
                for (File file : driver.getDrivers()) {
                    String device = file.getAbsolutePath();
                    devices.add(device);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return devices.toArray(new String[0]);
    }

}
